package com.share.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
public class IoUtil {

    public static String read(InputStream is) {
        byte[] bytes = readByte(is);
        return new String(bytes);
    }

    /**
     * 读取流
     *
     * @param is
     * @return
     */
    public static byte[] readByte(InputStream is) {
        if (is == null) {
            return null;
        }

        ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
        try {
            int len;
            byte[] temp = new byte[1024];
            while ((len = is.read(temp)) != -1) {
                outBuffer.write(temp, 0, len);
            }
        } catch (Exception e) {
            log.error("输入流读取异常", e);
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("输入流关闭异常", e);
                    return null;
                }
            }
        }

        return outBuffer.toByteArray();
    }


    public static boolean write(OutputStream out, String fileContent) {
        byte[] bytes = null;
        if (StringUtils.isNotBlank(fileContent)) {
            bytes = fileContent.getBytes();
        }
        return writeByte(out, bytes);
    }

    /**
     * 将数据写入文件
     *
     * @param out   输出流
     * @param bytes 文件内容(如果内容空,则只创建文件)
     * @return
     */
    public static boolean writeByte(OutputStream out, byte[] bytes) {
        if (out == null) {
            return false;
        }

        //文件中无内容
        if (bytes == null) {
            bytes = new byte[0];
        }

        try {
            out.write(bytes);
            return true;
        } catch (Exception e) {
            log.error("输出流写异常", e);
            return false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("输出流关闭异常", e);
                }
            }
        }
    }
}
